import store from '@/store';
import Setting from '@/setting';
// import router from '../router'
import websocketfun from './websocket/index';
import util from '@/libs/util';
import router from '@/router';

import { Message } from 'view-design';

let WebSocketObj = null;
let websocketUrl = null; // 默认地址
var lockReconnect = false; // 避免重复连接
var tt;
let linkTimes = 0; // 连接的次数 4次就提示连接失败
// 实例websocket
function createWebSocket () {
    websocketUrl = Setting.websocketUrl; // 默认地址\
    WebSocketObj = new WebSocket(websocketUrl);
    linkTimes++;
    initWebSocket();
}

// 初始化事件函数
function initWebSocket () {
    WebSocketObj.onclose = () => {
        reconnect();
    };

    WebSocketObj.onerror = (e) => {
        if (linkTimes >= 4) {
            console.log('重连连续失败3次，退出登陆')
        }
    };

    WebSocketObj.onopen = () => {
        // websocket打开
        // 重新登陆
        if (linkTimes > 1) {
        } else {
            let token = util.storage.get('token')
            if (token) {
                let msg = {
                    'msgType': 'screenAuth',
                    'checkType': 2,
                    'content': {
                        'token': token
                    }
                }
                sendSock(msg)
            }
            // 心跳检测重置
            heartCheck.start();
        }
    };

    WebSocketObj.onmessage = (event) => {
        // 拿到任何消息都说明当前连接是正常的
        linkTimes = 1;
        heartCheck.start();
        handleMsg(event);
    };
}

/**
 * 尝试重连
 * @param url
 */
function reconnect () {
    // 如果账号在别的地方登陆 || 或者token过期就不再重连了 || 主动退出 都不再重连
    if (lockReconnect) return;
    lockReconnect = true;
    // 没连接上会一直重连，设置延迟避免请求过多
    tt && clearTimeout(tt);
    tt = setTimeout(function () {
        createWebSocket(websocketUrl);
        lockReconnect = false;
    }, 5000); linkTimes = 0;
}

// 心跳检测
var heartCheck = {
    timeout: 20000, // 心跳检测时长
    timeoutObj: null, //  定时变量
    serverTimeoutObj: null, // 服务器超时
    start: function () {
        if (WebSocketObj.readyState === 1) {
            var self = this;
            // 重置心跳
            this.timeoutObj && clearTimeout(this.timeoutObj);
            this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
            this.timeoutObj = setTimeout(function () {
                // 这里发送一个心跳，后端收到后，返回一个心跳消息，
                let msg = {
                    msgType: 'ping',
                    checkType: 2

                };
                sendSock(msg);
                self.serverTimeoutObj = setTimeout(function () {
                    WebSocketObj.close();
                }, self.timeout);
            }, this.timeout);
        }
    }
};

// 数据接收处理
function handleMsg (e) {
    let msg = JSON.parse(e.data);
    let msgType = msg.msgType;
    switch (msgType) {
    // 大屏授权
    case 'screenAuthRes':
        websocketfun.screenAuthResHandle(msg);
        break;
    // 更新队列
    case 'queueListScreenRes':
        websocketfun.queueListScreenResHandle(msg);
        break;
    // 呼叫
    case 'queueCallScreenRes':
        websocketfun.queueCallScreenResHandle(msg);
        break;
    // 项目
    case 'projectListRes':
        websocketfun.projectListResHandle(msg);
        break;
    // 停止叫号
    case 'queueInfusionScreenRes':
        websocketfun.queueInfusionScreenResHandle(msg);
        break;
    // 错误
    case 'errorAuth':
        Message.error({ content: `${msg.content}`, duration: 3 });
        util.storage.remove('token')
        router.push('/login');
        break;
    // 错误
    case 'error':
        Message.error({ content: `${msg.content}`, duration: 3 });
        break;
    }
}

// 发送指令
function sendSock (agentData) {
    // 若是ws开启状态
    if (WebSocketObj && WebSocketObj.readyState === WebSocketObj.OPEN) {
        // 发送指令
        WebSocketObj.send(JSON.stringify(agentData));
    } else if (
        WebSocketObj &&
        WebSocketObj.readyState === WebSocketObj.CONNECTING
    ) {
        // 若是 正在开启状态，则等待1s后重新调用
        setTimeout(() => {
            sendSock(agentData);
        }, 1000);
    }
}

// 关闭websocket
function closeWebsocket () {
    if (WebSocketObj && WebSocketObj.readyState === WebSocketObj.OPEN) {
        WebSocketObj.close();
    }
}

export { sendSock, createWebSocket, closeWebsocket };
